package com.hou.netty.TestSystem;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {
    //压缩byte数组
    public static byte[] gzip(byte[] data) throws Exception {
        //byte字节流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(bos);//压缩流
        gzip.write(data);//将byte数组压缩后写到流中
        gzip.finish();
        gzip.close();
        byte[] ret = bos.toByteArray();//转数组
        bos.close();
        return ret;
    }

    //解压缩byte数组
    public static byte[] ungzip(byte[] data) throws Exception {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        GZIPInputStream gzip = new GZIPInputStream(bis);//解压缩流
        byte[] buf = new byte[1024];
        int num = -1;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((num = gzip.read(buf, 0, buf.length)) != -1) {//将数据压缩并读取到buf里
            bos.write(buf, 0, num);//将读取到的buf里面的数据马上写到bos流中
        }
        gzip.close();
        bis.close();
        byte[] ret = bos.toByteArray();
        bos.flush();
        bos.close();
        return ret;
    }
}
